<template>
  <div class="content-container">
    <el-card>
      <!-- 查询部分 -->
      <el-form :model="query" :inline="true" class="demo-form-inline">
        <el-form-item label="用户名称">
          <el-input v-model="query.nickname" clearable />
        </el-form-item>
        <el-form-item label="用户账号">
          <el-input v-model="query.account" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="formQuery(false)">查询</el-button>
          <el-button type="warning" @click="formQuery(true)">重置</el-button>
          <el-button type="primary" @click="openDialog(null)">新增</el-button>

          <el-popconfirm confirm-button-text="确认" cancel-button-text="取消" title="确认删除选中数据?" @confirm="removeRows"
            width="200px">
            <template #reference>
              <el-button type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </el-form-item>
      </el-form>
      <!-- 数据部分 -->
      <el-table max-height="600px" :data="tableData" stripe style="width: 100%; margin-top: 10px" ref="tableDataRef">
        <el-table-column type="selection" />
        <el-table-column prop="nickname" label="姓名" />
        <el-table-column prop="deptName" label="部门" />
        <el-table-column prop="postName" label="职位" />
        <el-table-column prop="account" label="账号" />
        <el-table-column prop="avatar" label="头像">
          <template #default="scope">
            <el-avatar :size="25" :src="scope.row.avatar ? scope.row.avatar : '无'" />
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="联系方式" />
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-popconfirm confirm-button-text="确认" cancel-button-text="取消" title="确认切换用户状态?"
              @confirm="switchStatus(scope.row.id)" width="200px">
              <template #reference>
                <el-tag style="cursor: pointer" :type="scope.row.status === 1 ? 'success' : 'danger'">
                  {{ scope.row.statusName }}
                </el-tag>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column prop="updateTime" label="修改时间" />
        <el-table-column fixed="right" label="操作">
          <template #default="scope">
            <el-button @click="viewDialog(scope.row)" link type="success">
              查看
            </el-button>
            <el-button @click="openDialog(scope.row)" link type="primary">
              编辑
            </el-button>
            <el-button @click="r2uDialog(scope.row.id)" link type="danger">
              授权
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div style="margin-top: 20px">
        <el-pagination v-model:current-page="query.current" v-model:page-size="query.size"
          :page-sizes="[100, 200, 300, 400]" small background layout="total, sizes, prev, pager, next, jumper"
          :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>

      <el-dialog v-model="dialogVisible" :title="(formData.id ? '编辑' : '新增') + '用户信息'" width="60%" :show-close="false"
        :close-on-click-modal="false">
        <el-form :rules="rules" :model="formData" class="demo-form-inline" ref="formDataRef">
          <el-form-item prop="nickname" label="用户名称">
            <el-input v-model="formData.nickname" clearable />
          </el-form-item>
          <el-form-item prop="account" label="用户账号">
            <el-input v-model="formData.account" clearable />
          </el-form-item>
          <el-form-item v-if="!formData.id" prop="password" label="用户密码">
            <el-input v-model="formData.password" clearable />
          </el-form-item>
          <el-form-item prop="deptId" label="所属部门">
            <el-tree-select v-model="formData.deptId" :data="tenantUser.deptList" :render-after-expand="false"
              :props="{ label: 'name', value: 'id' }" clearable searchable filterable check-strictly accordion />
          </el-form-item>
          <el-form-item prop="postId" label="所属职位">
            <el-select v-model="formData.postId" clearable filterable>
              <el-option v-for="item in tenantUser.posts" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item prop="status" label="用户状态">
            <el-select v-model="formData.status" clearable filterable>
              <el-option v-for="item in [
                { label: '正常', value: 1 },
                { label: '禁用', value: 0 },
              ]" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item prop="avatar" label="用户头像">
            <el-input v-model="formData.avatar" clearable />
          </el-form-item>
          <el-form-item prop="email" label="用户邮箱">
            <el-input v-model="formData.email" clearable />
          </el-form-item>
          <el-form-item prop="phone" label="联系方式">
            <el-input v-model="formData.phone" clearable />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="formSubmit">确认</el-button>
          </span>
        </template>
      </el-dialog>

      <el-dialog v-model="viewVisible" width="60%" :show-close="false" :close-on-click-modal="false">
        <el-input v-model="viewData.nickname" disabled>
          <template #prepend>用户名称</template>
        </el-input>
        <el-input v-model="viewData.account" disabled>
          <template #prepend>用户账号</template>
        </el-input>
        <el-input v-model="viewData.avatar" disabled>
          <template #prepend>用户头像</template>
        </el-input>
        <el-input v-model="viewData.email" disabled>
          <template #prepend>用户邮箱</template>
        </el-input>
        <el-input v-model="viewData.phone" disabled>
          <template #prepend>联系方式</template>
        </el-input>
        <el-input v-model="viewData.statusName" disabled>
          <template #prepend>用户状态</template>
        </el-input>
        <el-input v-model="viewData.deptName" disabled>
          <template #prepend>所属部门</template>
        </el-input>
        <el-input v-model="viewData.postName" disabled>
          <template #prepend>所属职位</template>
        </el-input>
        <el-input v-model="viewData.createTime" disabled>
          <template #prepend>创建时间</template>
        </el-input>
        <el-input v-model="viewData.updateTime" disabled>
          <template #prepend>修改时间</template>
        </el-input>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="viewVisible = false">关闭</el-button>
          </span>
        </template>
      </el-dialog>
      <el-dialog v-model="r2uVisible" title="用户授权" width="40%" :show-close="false" :close-on-click-modal="false">
        <el-tree style="max-width: 600px" ref="treeRef" check-strictly :data="tenantUser.roles" show-checkbox
          node-key="id" :props="{ label: 'name' }" default-expand-all />
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="r2uVisible = false">取消</el-button>
            <el-button type="primary" @click="r2uConfirm">确认</el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>
<script setup lang="ts" name="User">
import { onMounted, ref, reactive, toRefs } from 'vue'
import type {
  TenantUserVo,
  User,
  UserModDTO,
  UserQueryDTO,
  UserVo,
} from '@/api/acl/user/type'
import {
  gatherInfo,
  r2u,
  switchUser,
  userAdd,
  userDel,
  userMod,
  userQuery,
  userRoles,
} from '@/api/acl/user'
import { ElNotification } from 'element-plus'
const treeRef = ref()
const formDataRef = ref()
const tableDataRef = ref()
const initQuery = () => {
  return { current: 1, size: 10 } as UserQueryDTO
}
const state = reactive<any>({
  query: initQuery(),
  tableData: [] as User[],
  total: 0,
  dialogVisible: false,
  viewVisible: false,
  viewData: {} as UserVo,
  formData: {} as UserModDTO,
  tenantUser: {} as TenantUserVo,
  r2uVisible: false,
  userId: null,
  rules: {
    nickname: [
      { required: true, message: '用户名称不能为空', trigger: 'blur' },
    ],
    account: [{ required: true, message: '用户账号不能为空', trigger: 'blur' }],
    password: [
      { required: true, message: '用户密码不能为空', trigger: 'blur' },
    ],
    deptId: [{ required: true, message: '部门不能为空', trigger: 'change' }],
    status: [{ required: true, message: '状态不能为空', trigger: 'change' }],
    postId: [{ required: true, message: '职位不能为空', trigger: 'change' }],
  },
})
const {
  query,
  tableData,
  total,
  dialogVisible,
  formData,
  rules,
  viewVisible,
  viewData,
  tenantUser,
  r2uVisible,
  userId,
} = toRefs(state)
const openDialog = (data: any) => {
  if (formDataRef.value) {
    formDataRef.value.resetFields()
  }

  formData.value = data == null ? {} : data
  dialogVisible.value = true
}
const viewDialog = (data: any) => {
  viewVisible.value = true
  viewData.value = data
}
const handleSizeChange = (size: number) => {
  query.value.size = size
  buildTable()
}
const handleCurrentChange = (current: number) => {
  query.value.current = current
  buildTable()
}
const r2uDialog = async (id: string) => {
  r2uVisible.value = true
  userId.value = id
  const result = await userRoles(id)
  treeRef.value!.setCheckedKeys(result.data, true)
}
const r2uConfirm = async () => {
  await r2u({
    userId: userId!.value,
    roleIds: treeRef.value!.getCheckedKeys(false),
  })
  r2uVisible.value = false
  userId.value = null
}
onMounted(() => {
  buildTable()
  gatherUser()
})
const buildTable = async () => {
  const result = await userQuery(query.value)
  tableData.value = result.data.rows
  total.value = result.data.total
}
const gatherUser = async () => {
  const result = await gatherInfo()
  tenantUser.value = result.data
}
const formQuery = (reset: boolean) => {
  reset ? (query.value = initQuery()) : query.value
  buildTable()
}
const formSubmit = async () => {
  await formDataRef.value?.validate()
  if (formData.value.id) {
    await userMod(formData.value)
  } else {
    await userAdd(formData.value)
  }
  dialogVisible.value = false
  await buildTable()
}
const switchStatus = async (id: string) => {
  await switchUser(id)
  await buildTable()
}
const removeRows = async () => {
  const rows = tableDataRef.value.getSelectionRows()
  if (rows.length == 0) {
    ElNotification({
      title: '删除失败',
      message: '请选择要删除的数据',
      type: 'warning',
    })
    return
  }
  const ids = rows.map((each: any) => each.id)
  await userDel({ ids: ids })
  await buildTable()
}
</script>


<style scoped lang="scss">
.content-container {
  padding: 12px;
}
</style>